#include "USB_ProcessList_Model.h"

USB_ProcessList_Model* USB_ProcessList_Model::m_instance = nullptr;

USB_ProcessList_Model::USB_ProcessList_Model(QObject *parent)
    : QAbstractListModel(parent)
{
    qDebug() << "USB_ProcessList_Model instance created";
    // 初始化CSV文件路径（程序目录下的material_save.csv）
    QString appDir = QCoreApplication::applicationDirPath();
    m_csvFilePath = appDir + QDir::separator() + "USB_Process_Lists.csv";
    qDebug() << "材料CSV文件路径：" << m_csvFilePath;

    // 初始化时扫描文件并尝试加载数据
    scanFiles();
    readFromCsv();
}

USB_ProcessList_Model::~USB_ProcessList_Model()
{
    qDebug() << "USB_ProcessList_Model instance destroyed";
    m_instance = nullptr;
}

USB_ProcessList_Model* USB_ProcessList_Model::getInstance()
{
    if (!m_instance) {
        m_instance = new USB_ProcessList_Model();
    }
    return m_instance;
}

int USB_ProcessList_Model::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;
    return m_materials.count();
}

QVariant USB_ProcessList_Model::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() >= m_materials.count())
        return QVariant();

    const MaterialData &material = m_materials[index.row()];

    switch (role) {
    case MaterialNameRole: return material.materialName;
    case MaterialColorRole: return material.material_Color;
    case MaterialIDRole: return material.material_ID;
    case SpecificationRole: return material.specification;
    case CuttingLengthRole: return material.cuttingLength;
    case LeftAngleRole: return material.leftAngle;
    case RightAngleRole: return material.rightAngle;
    case RawMaterialLengthRole: return material.rawMaterialLength;
    case RemainingLengthRole: return material.remainingLength;
    case TotalCountRole: return material.totalCount;
    case ProcessedCountRole: return material.processedCount;
    default: return QVariant();
    }
}

bool USB_ProcessList_Model::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (!index.isValid() || index.row() >= m_materials.count())
        return false;

    MaterialData &material = m_materials[index.row()];

    switch (role) {
    case ProcessedCountRole:
        material.processedCount = value.toInt();
        break;
    default:
        return false;
    }

    emit dataChanged(index, index, {role});
    return true;
}

QHash<int, QByteArray> USB_ProcessList_Model::roleNames() const
{
    QHash<int, QByteArray> roles;
    roles[MaterialNameRole] = "materialName";
    roles[MaterialColorRole] = "material_Color";
    roles[MaterialIDRole] = "material_ID";
    roles[SpecificationRole] = "specification";
    roles[CuttingLengthRole] = "cuttingLength";
    roles[LeftAngleRole] = "leftAngle";
    roles[RightAngleRole] = "rightAngle";
    roles[RawMaterialLengthRole] = "rawMaterialLength";
    roles[RemainingLengthRole] = "remainingLength";
    roles[TotalCountRole] = "totalCount";
    roles[ProcessedCountRole] = "processedCount";
    return roles;
}

// CSV文件操作
bool USB_ProcessList_Model::saveToCsv()
{
    QFile file(m_csvFilePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qWarning() << "无法打开材料CSV文件写入：" << file.errorString();
        return false;
    }

    QTextStream out(&file);
    // 写入CSV头部
    out << "materialName,material_Color,material_ID,specification,cuttingLength,"
        << "leftAngle,rightAngle,rawMaterialLength,remainingLength,totalCount,processedCount\n";

    // 写入数据行
    for (const auto &material : m_materials) {
        out << material.materialName << ","
            << material.material_Color << ","
            << material.material_ID << ","
            << material.specification << ","
            << material.cuttingLength << ","
            << material.leftAngle << ","
            << material.rightAngle << ","
            << material.rawMaterialLength << ","
            << material.remainingLength << ","
            << material.totalCount << ","
            << material.processedCount << "\n";
    }

    file.close();
    qDebug() << "材料数据已保存到CSV：" << m_csvFilePath;
    return true;
}

bool USB_ProcessList_Model::readFromCsv()
{
    QFile file(m_csvFilePath);
    if (!file.exists()) {
        qDebug() << "材料CSV文件不存在：" << m_csvFilePath;
        return false;
    }

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "无法打开材料CSV文件读取：" << file.errorString();
        return false;
    }

    QTextStream in(&file);
    QVector<MaterialData> loadedData;

    // 跳过头部
    QString header = in.readLine();
    Q_UNUSED(header);

    // 解析数据行
    while (!in.atEnd()) {
        QString line = in.readLine();
        QStringList fields = line.split(",");
        if (fields.size() != 11) {
            qWarning() << "材料CSV格式错误，跳过行：" << line;
            continue;
        }

        MaterialData material;
        material.materialName = fields[0];
        material.material_Color = fields[1];
        material.material_ID = fields[2];
        material.specification = fields[3];
        material.cuttingLength = fields[4];
        material.leftAngle = fields[5];
        material.rightAngle = fields[6];
        material.rawMaterialLength = fields[7];
        material.remainingLength = fields[8];
        material.totalCount = fields[9].toInt();
        material.processedCount = fields[10].toInt();

        loadedData.append(material);
    }

    file.close();
    setMaterialList(loadedData);
    qDebug() << "已从CSV加载" << loadedData.size() << "条材料数据";
    return true;
}

void USB_ProcessList_Model::clearCsvFile()
{
    QFile file(m_csvFilePath);
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        file.close();
        qDebug() << "材料CSV文件已清空：" << m_csvFilePath;
    } else {
        qWarning() << "无法清空材料CSV文件：" << file.errorString();
    }
}

// 数据操作
QVariantMap USB_ProcessList_Model::get(int index) const
{
    QVariantMap map;
    if (index < 0 || index >= m_materials.size()) {
        return map;
    }

    const MaterialData &material = m_materials[index];
    map["materialName"] = material.materialName;
    map["material_Color"] = material.material_Color;
    map["material_ID"] = material.material_ID;
    map["specification"] = material.specification;
    map["cuttingLength"] = material.cuttingLength;
    map["leftAngle"] = material.leftAngle;
    map["rightAngle"] = material.rightAngle;
    map["rawMaterialLength"] = material.rawMaterialLength;
    map["remainingLength"] = material.remainingLength;
    map["totalCount"] = material.totalCount;
    map["processedCount"] = material.processedCount;
    return map;
}

void USB_ProcessList_Model::addMaterial(const MaterialData &data)
{
    beginInsertRows(QModelIndex(), m_materials.count(), m_materials.count());
    m_materials.append(data);
    endInsertRows();
    emit countChanged();
    emit modelDataUpdated();
}

void USB_ProcessList_Model::clear()
{
    beginResetModel();
    m_materials.clear();
    endResetModel();
    emit countChanged();
    emit dataCleared();
    emit modelDataUpdated();
    clearCsvFile();
    qDebug() << "材料数据已清空";
}

void USB_ProcessList_Model::updateProcessedCount(int index, int count)
{
    if (index < 0 || index >= m_materials.size()) {
        return;
    }

    m_materials[index].processedCount = count;
    emit dataChanged(createIndex(index, 0), createIndex(index, 0), {ProcessedCountRole});
}

void USB_ProcessList_Model::incrementWorkedCount(int index)
{
    // 检查索引是否有效
    if (index < 0 || index >= m_materials.size()) {
        qWarning() << "Invalid index for incrementWorkedCount:" << index;
        return;
    }

    // 增加已加工数量
    m_materials[index].processedCount++;

    // 通知视图：指定索引的ProcessedCountRole数据已更新
    emit dataChanged(createIndex(index, 0), createIndex(index, 0), {ProcessedCountRole});
}

void USB_ProcessList_Model::setMaterialList(const QVector<MaterialData> &materialList)
{
    beginResetModel();
    m_materials = materialList;
    endResetModel();
    emit countChanged();
    emit modelDataUpdated();
}

// 属性实现
int USB_ProcessList_Model::count() const
{
    return m_materials.count();
}

void USB_ProcessList_Model::setCount(int newCount)
{
    if (m_count == newCount)
        return;
    m_count = newCount;
    emit countChanged();
}

QString USB_ProcessList_Model::currentFile() const
{
    return m_currentFile;
}

void USB_ProcessList_Model::setCurrentFile(const QString &currentFile)
{
    if (m_currentFile != currentFile) {
        m_currentFile = currentFile;
        emit currentFileChanged();
        setStatusMessage("已选择文件: " + currentFile);
    }
}

QStringList USB_ProcessList_Model::fileList() const
{
    return m_fileList;
}

QString USB_ProcessList_Model::statusMessage() const
{
    return m_statusMessage;
}

// 其他方法
void USB_ProcessList_Model::parseSelectedFile()
{
    if (m_currentFile.isEmpty()) {
        setStatusMessage("请选择一个文件");
        emit showMessage("请先从下拉列表中选择一个文件");
        return;
    }

    QString filePath = getProcessListsPath() + "/" + m_currentFile;
    QFile file(filePath);

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QString error = "无法打开文件: " + m_currentFile + " (" + file.errorString() + ")";
        setStatusMessage(error);
        emit showMessage(error);
        return;
    }

    QTextStream in(&file);
    QString csvData = in.readAll();
    file.close();

    if (parseCsvData(csvData)) {
        setStatusMessage("已成功解析文件: " + m_currentFile + "，共 " + QString::number(m_materials.count()) + " 条记录");
        emit showMessage("解析成功，共找到 " + QString::number(m_materials.count()) + " 种不同的材料");
        saveToCsv();  // 解析后自动保存
    }
}

void USB_ProcessList_Model::scanFiles()
{
    QString path = getProcessListsPath();
    QDir dir(path);

    if (!dir.exists()) {
        if (dir.mkpath(path)) {
            qDebug() << "创建USB_ProcessLists文件夹成功";
            setStatusMessage("已创建USB_ProcessLists文件夹");
        } else {
            qDebug() << "创建USB_ProcessLists文件夹失败";
            setStatusMessage("创建USB_ProcessLists文件夹失败");
            return;
        }
    }

    QStringList nameFilters = {"*.txt", "*.csv"};
    QFileInfoList fileInfoList = dir.entryInfoList(nameFilters, QDir::Files, QDir::Time);
    QStringList newFileList;

    foreach (const QFileInfo &fileInfo, fileInfoList) {
        newFileList << fileInfo.fileName();
    }

    if (newFileList != m_fileList) {
        m_fileList = newFileList;
        emit fileListChanged();

        if (!m_fileList.contains(m_currentFile)) {
            setCurrentFile("");
        }

        setStatusMessage("已扫描到 " + QString::number(m_fileList.count()) + " 个文件");
    }
}

bool USB_ProcessList_Model::parseCsvData(const QString &data)
{
    beginResetModel();
    m_materials.clear();

    QStringList lines = data.split('\n');
    int lineNumber = 0;

    foreach (QString line, lines) {
        lineNumber++;
        line = line.trimmed();
        if (line.isEmpty()) continue;

        QString lowerLine = line.toLower();
        if (lowerLine.contains("ten vat lieu") || lowerLine.contains("dinh hinh")) {
            qDebug() << "跳过标题行: " << lineNumber;
            continue;
        }

        QStringList fields;
        bool inQuotes = false;
        QString currentField;

        for (QChar c : line) {
            if (c == '"') {
                inQuotes = !inQuotes;
            } else if (c == ',' && !inQuotes) {
                fields.append(currentField.trimmed());
                currentField.clear();
            } else {
                currentField += c;
            }
        }
        fields.append(currentField.trimmed());

        if (fields.count() < 13) {
            qWarning() << "行" << lineNumber << "格式不正确，跳过";
            continue;
        }

        MaterialData material;
        material.materialName = fields[1];
        material.material_Color = fields[2];
        material.material_ID = fields[3];
        material.specification = fields[4];
        material.cuttingLength = fields[7];
        material.leftAngle = fields[8];
        material.rightAngle = fields[9];
        material.rawMaterialLength = fields[11];
        material.remainingLength = fields[12];
        material.totalCount = 1;
        material.processedCount = 0;

        bool found = false;
        for (int i = 0; i < m_materials.count(); i++) {
            MaterialData &existing = m_materials[i];
            if (existing.materialName == material.materialName &&
                existing.material_Color == material.material_Color &&
                existing.material_ID == material.material_ID &&
                existing.specification == material.specification &&
                existing.cuttingLength == material.cuttingLength &&
                existing.leftAngle == material.leftAngle &&
                existing.rightAngle == material.rightAngle &&
                existing.rawMaterialLength == material.rawMaterialLength &&
                existing.remainingLength == material.remainingLength) {

                existing.totalCount++;
                found = true;
                break;
            }
        }

        if (!found) {
            m_materials.append(material);
        }
    }

    endResetModel();
    return true;
}

QString USB_ProcessList_Model::getProcessListsPath() const
{
    return QCoreApplication::applicationDirPath() + "/USB_ProcessLists";
}

void USB_ProcessList_Model::setStatusMessage(const QString &message)
{
    if (m_statusMessage != message) {
        m_statusMessage = message;
        emit statusMessageChanged();
    }
}
